package com.qudian.pay.core.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import com.google.common.collect.Maps;

/**
 * @Description: IP工具
 * @ClassName: IPUtils
 * @author gaoxiang
 * @date 2016年5月17日 下午6:53:13
 */ 
public class IPUtils {
	
	private static Map<String, String> ip4s = Maps.newHashMap();
	
	private static Map<String, String> ip6s = Maps.newHashMap();
	
	private static String ipAddress = null;
	static {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			String hostname = addr.getHostName();
			if ("127.0.0.1".equals(addr.getHostAddress())) {
				Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
				while (e.hasMoreElements()) {
					NetworkInterface netface = e.nextElement();
					String name = netface.getName();
					if (!name.startsWith("lo")) {
						Enumeration<InetAddress> e2 = netface.getInetAddresses();
						while (e2.hasMoreElements()) {
							InetAddress ip2 =  e2.nextElement();
							if (ip2 instanceof java.net.Inet4Address) {
								ip4s.put(name, ip2.getHostAddress());
							} else {
								ip6s.put(name, ip2.getHostAddress());
							}
						}
					}
				}
			} else {
				ip4s.put(hostname, addr.getHostAddress());
			}
		} catch (Exception e) {}
	}
	
	/**
	 * @Description: 得到IPV4模式的唯一IP地址，如果有多个，那么随机获得一个
	 * @return String 返回类型
	 * @author gaoxiang
	 * @date 2016年5月17日 下午6:51:52
	 */
	public static String getIp4Single() {
		if (ip4s.isEmpty()) {
			return "127.0.0.1";
		}
		if (null == ipAddress) {
			Iterator<String> iter = ip4s.values().iterator();
			while (iter.hasNext()) {
				ipAddress = iter.next();
				if (!"127.0.0.1".equals(ipAddress)) {
					break;
				}
			}
		}
		if (null == ipAddress) {
			ipAddress = "127.0.0.1";
		}
		return ipAddress;
	}
}
